package com.cloudcc.mobile.view.activity;

import java.util.ArrayList;
import java.util.HashMap;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.provider.MediaStore;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.GridView;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;

import com.cloudcc.cloudframe.model.Album;
import com.cloudcc.cloudframe.util.DensityUtils;
import com.cloudcc.mobile.AppContext;
import com.cloudcc.mobile.R;
import com.cloudcc.mobile.adapter.AlbumListViewAdapter;
import com.cloudcc.mobile.adapter.ChoicePhotoAdapter;
import com.cloudcc.mobile.adapter.GridViewAdapter;
import com.cloudcc.mobile.util.Tools;
import com.cloudcc.mobile.util.photo.Constants;
import com.cloudcc.mobile.util.photo.TestEvent;
import com.cloudcc.mobile.util.photo.Util;
import com.cloudcc.mobile.view.base.BaseActivity;
import com.cloudcc.mobile.weight.LoadingView;

import de.greenrobot.event.EventBus;

/**
 * 图片选择页面
 * 
 * @author seven
 * 
 */
public class SelectPhotoActivity extends BaseActivity implements
		 OnClickListener {
	private AlbumListViewAdapter listViewAdapter;
	private ArrayList<Album> albums;
	private GridView gridView;
	private GridViewAdapter gridViewAdapter;
	private ArrayList<String> mPhotos = new ArrayList<String>();
	private ArrayList<String> mSelectedPhotos = new ArrayList<String>();
	private HashMap<String, ImageView> hashMap = new HashMap<String, ImageView>();
	private LinearLayout selectedImageLayout;
	private HorizontalScrollView scroll_view;
	private ImageView btn_cancel;
	private TextView title;
	private Button okButton;
	private EventBus eventBus;
	private boolean isfanhui = true;
	private ChoicePhotoAdapter choiceadapter;
	private ListView listView;
	private Context context;
	private PopupWindow popupWindow;
	private LoadingView loading;
	private RelativeLayout popup;

	/**
	 * Called when the activity is first created.
	 */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		try {
			context = this;
			setupView();
			addListener();
		} catch (Exception e) {
			Tools.handle(e);
		}

	}
	
	@Override
	public int getLayoutId() {
		return R.layout.select_photo;
	}

	private void setupView() {
		// albums = getAlbums();
		new Thread() {
			public void run() {
				albums = getAlbums();
			};
		}.start();
		eventBus = EventBus.getDefault();
		eventBus.register(this);
		gridView = (GridView) this.findViewById(R.id.grid_view);
		selectedImageLayout = (LinearLayout) findViewById(R.id.selected_image_layout);
		scroll_view = (HorizontalScrollView) findViewById(R.id.scrollview);
		btn_cancel = (ImageView) this.findViewById(R.id.cancelbtn);
		title = (TextView) this.findViewById(R.id.title);
		title.setWidth((int) DensityUtils.getScreenWidth(mContext) / 3);
		popup = (RelativeLayout) this.findViewById(R.id.popup);
		okButton = (Button) this.findViewById(R.id.ok_button);
		loading = (LoadingView) this.findViewById(R.id.loading);
		okButton.setText("完成("
				+ (AppContext.isSelectedNum + mSelectedPhotos.size()) + "/9)");
		loading.setVisibility(View.VISIBLE);
		gridView.setVisibility(View.INVISIBLE);
		title.setText("Camera");
		title.setOnClickListener(this);
		btn_cancel.setOnClickListener(this);
		okButton.setOnClickListener(this);
		popup.setOnClickListener(this);
		new Thread() {
			public void run() {
				mPhotos = getPhotos("Camera");
				handler.sendEmptyMessage(1);
			};
		}.start();
	}

	Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case 1:
				loading.setVisibility(View.GONE);
				gridView.setVisibility(View.VISIBLE);
				gridViewAdapter = new GridViewAdapter(getApplicationContext(),
						mPhotos, mSelectedPhotos);
				gridView.setAdapter(gridViewAdapter);
				choicePhoto();
				break;
			}
		};
	};

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.title:
			if (albums.size() < 1) {
				return;
			} else {
				ShowPopup(v);
			}
			break;
		case R.id.cancelbtn:
			SelectPhotoActivity.this.finish();
			break;
		case R.id.popup:
			if (albums.size() < 1) {
				return;
			} else {
				ShowPopup(v);
			}
			break;
		case R.id.ok_button:
			if (mSelectedPhotos.size() > 0) {
				Intent intent = new Intent();
				isfanhui = true;
				AppContext.selectPhotos = mSelectedPhotos;
				setResult(Activity.RESULT_OK, intent);
				finish();
			} else {
				Tools.showInfo(context, "亲，您还没有选择图片哦！");
			}
			break;

		default:
			break;
		}

	}

	private void addListener() {
		choicePhoto();
	}

	private void choicePhoto() {
		gridViewAdapter
				.setOnItemClickListener(new GridViewAdapter.OnItemClickListener() {
					@Override
					public void onItemClick(final ToggleButton toggleButton,
							int position, final String path, boolean isChecked) {
						if ((AppContext.isSelectedNum + mSelectedPhotos
								.size()) >= 9) {
							toggleButton.setChecked(false);
							if (!removePath(path)) {
								Toast.makeText(SelectPhotoActivity.this,
										"只能选择9张图片", 200).show();
							}
							return;
						}
						if (isChecked) {
							if (!hashMap.containsKey(path)) {
								ImageView imageView = (ImageView) LayoutInflater
										.from(SelectPhotoActivity.this)
										.inflate(R.layout.choose_imageview,
												selectedImageLayout, false);
								selectedImageLayout.addView(imageView);
								imageView.postDelayed(new Runnable() {
									@Override
									public void run() {
										int off = selectedImageLayout
												.getMeasuredWidth()
												- scroll_view.getWidth();
										if (off > 0) {
											scroll_view.smoothScrollTo(off, 0);
										}

									}
								}, 100);

								hashMap.put(path, imageView);
								mSelectedPhotos.add(path);
								Constants.imageLoader.displayImage("file://"
										+ mPhotos.get(position), imageView,
										Constants.image_display_options,
										new Util.AnimateFirstDisplayListener());
								imageView
										.setOnClickListener(new View.OnClickListener() {

											@Override
											public void onClick(View v) {
												toggleButton.setChecked(false);
												removePath(path);
											}
										});
								okButton.setText("完成("
										+ (AppContext.isSelectedNum + mSelectedPhotos
												.size()) + "/9)");
							}
						} else {
							removePath(path);
						}
					}
				});
	}

	protected void ShowPopup(View parent) {
		if (popupWindow == null) {
			View view = LayoutInflater.from(this).inflate(
					R.layout.choice_photo, null);
			listView = (ListView) view.findViewById(R.id.listview);
			choiceadapter = new ChoicePhotoAdapter(context, albums);
			listView.setAdapter(choiceadapter);
			WindowManager wm = getWindowManager();
			int width = wm.getDefaultDisplay().getWidth();
			popupWindow = new PopupWindow(view, width,
					(int) DensityUtils.getScreenHeight(mContext) / 2);
			// popupWindow.setAnimationStyle(R.style.popwin_anim_style);
		}
		popupWindow.setFocusable(true);
		popupWindow.setOutsideTouchable(true);
		// 这个是为了点击“返回Back”也能使其消失，并且并不会影响你的背景
		popupWindow.setBackgroundDrawable(new BitmapDrawable());
		WindowManager windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
		// 显示的位置为:屏幕的宽度的一半-PopupWindow的高度的一半
		int xPos = parent.getWidth() / 2 - popupWindow.getWidth() / 2;
		popupWindow.showAsDropDown(parent, xPos, 0);
		listView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				AppContext.choiceposition = arg2;
				TestEvent event = new TestEvent("list_view_item_click");
				isfanhui = false;
				Bundle bundle = new Bundle();
				bundle.putInt("position", arg2);
				event.set_bundle(bundle);
				eventBus.post(event);
				if (popupWindow != null) {
					popupWindow.dismiss();
				}
			}
		});
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			SelectPhotoActivity.this.finish();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	private ArrayList<String> getPathList() {
		ArrayList<String> list = new ArrayList<String>();
		ContentResolver contentResolver = getContentResolver();
		String[] projection = new String[] { MediaStore.Images.Media.DATA };
		Cursor cursor = contentResolver.query(
				MediaStore.Images.Media.EXTERNAL_CONTENT_URI, projection, null,
				null, MediaStore.Images.Media.BUCKET_DISPLAY_NAME);
		while (cursor.moveToNext()) {
			list.add(cursor.getString(0));
		}
		if (cursor != null) {
			cursor.close();
		}
		return list;
	}

	public ArrayList<Album> getAlbums() {
		ArrayList<Album> albums = new ArrayList<Album>();
		ArrayList<String> list = getPathList();
		int size = list.size();
		if (size > 0) {
			String currentDir = "";
			int currentNum = 0;
			String currentUrl = "";
			for (int i = 0; i < size; i++) {
				String path = list.get(i);
				String dirName = Util.getDir(path);
				if ("".equals(currentDir)) {
					currentDir = dirName;
					currentNum = 1;
					currentUrl = path;
					continue;
				}
				if (currentDir.equals(dirName)) {
					currentNum++;
				} else {
					Album album = new Album();
					album.mName = currentDir;
					album.mNum = "(" + currentNum + ")";
					album.mCoverUrl = currentUrl;
					albums.add(album);

					currentDir = dirName;
					currentNum = 1;
					currentUrl = path;
				}
			}
			Album album = new Album();
			album.mName = currentDir;
			album.mNum = "(" + currentNum + ")";
			album.mCoverUrl = currentUrl;
			albums.add(album);
		}
		return albums;
	}

	/**
	 * 获取一个相册中所有图片路径
	 * 
	 * @param album_dir
	 * @return
	 */
	public ArrayList<String> getPhotos(String album_dir) {
		ArrayList<String> photos = new ArrayList<String>();
		ContentResolver contentResolver = getContentResolver();
		String[] projection = new String[] { MediaStore.Images.Media.DATA };
		Cursor cursor = contentResolver.query(
				MediaStore.Images.Media.EXTERNAL_CONTENT_URI, projection, null,
				null, MediaStore.Images.Media._ID + " DESC");
		cursor.moveToFirst();
		int fileNum = cursor.getCount();

		for (int counter = 0; counter < fileNum; counter++) {
			String path = cursor.getString(cursor
					.getColumnIndex(MediaStore.Video.Media.DATA));
			// 获取路径中文件的目录
			String file_dir = Util.getDir(path);
			if (file_dir.equals(album_dir))
				photos.add(path);
			cursor.moveToNext();
		}
		if (cursor != null) {
			cursor.close();
		}

		return photos;
	}

	private boolean removePath(String path) {
		if (hashMap.containsKey(path)) {
			selectedImageLayout.removeView(hashMap.get(path));
			hashMap.remove(path);
			removeOneData(mSelectedPhotos, path);
			okButton.setText("完成("
					+ (AppContext.isSelectedNum + mSelectedPhotos.size())
					+ "/9)");
			return true;
		} else {
			return false;
		}
	}

	private void removeOneData(ArrayList<String> arrayList, String s) {
		for (int i = 0; i < arrayList.size(); i++) {
			if (arrayList.get(i).equals(s)) {
				arrayList.remove(i);
				return;
			}
		}
	}

	// eventbus接收到通知事件，发生改变
	public void onEvent(TestEvent event) {
		if (event.get_string().equals("list_view_item_click")) {
			Bundle bundle = event.get_bundle();
			gridView.setVisibility(View.VISIBLE);
			String album_dir = choiceadapter.getItem(bundle.getInt("position"))
					.getmName();
			title.setText("");
			title.setText(album_dir);
			mPhotos = getPhotos(album_dir);
			gridViewAdapter = new GridViewAdapter(getApplicationContext(),
					mPhotos, mSelectedPhotos);
			gridView.setAdapter(gridViewAdapter);
			choicePhoto();
		}
	}
}
